package cn.picclife.mwx.manager.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.builder.ResultMapResolver;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;

import cn.picclife.mwx.manager.base.BaseResult1;
import cn.picclife.mwx.manager.sys.model.bo.UserSessionBo;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	private static final String loginPage = "/login.html";

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav)
			throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		// session管理和登陆判断
		Boolean isLogin = false;

		UserSessionBo user = (UserSessionBo) request.getSession().getAttribute("user");

		if (null !=user&&StringUtils.isNotBlank(user.getOptNo())) {
			isLogin = true;
		}
		
		if (!isLogin) {
			String requestType = request.getHeader("x-requested-with");
			boolean isAjax = false;
			if ("XMLHttpRequest".equals(requestType)) {
				isAjax = true;
			}
			// 判断是否是ajax请求
			if (isAjax) {
				BaseResult1 result = new BaseResult1();
				result.setRet(BaseResult1.SESSION_ERROR);
				result.setMsg("页面过期，请重新登录");
				PrintWriter out = response.getWriter();
				response.setStatus(HttpStatus.BAD_REQUEST.value());
				out.print(JSON.toJSONString(result));
				out.flush();
				out.close();
			} else {
				String ctx = request.getContextPath();
				// 未登录
				PrintWriter out = response.getWriter();
				StringBuilder builder = new StringBuilder();
				builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
				builder.append("alert(\"页面过期，请重新登录\");");
				builder.append("window.top.location.href=\"");
				builder.append(ctx + loginPage);
				builder.append("\";");
				builder.append("</script>");
				out.print(builder.toString());
				out.close();
			}
			return false;
		}
		return true;
	}
}
